<?php

namespace app\api\service;

use EasyWeChat\Factory;
use app\model\User as UserModel;


class PayConfig {

    private $config;
    public $pay_status = -1;  //-1关闭 0表示直接成功 大于0 表示以该小金额
    public $error_msg = '';
    //小程序支付配置
    public function playConfig() {
        $sysConfig = getConfByType('basic');
        $arr['xcx_appid'] = $sysConfig['miniapp_app_id'];
        $arr['pay_num'] = $sysConfig['pay_num'];
        $arr['pay_key'] = $sysConfig['pay_key'];
        $arr['api_url'] = request()->domain();

        $config = ['app_id' => $arr['xcx_appid'], 'mch_id' => $arr['pay_num'], 'key' => $arr['pay_key'], // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => ROOT_PATH . 'cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path' => ROOT_PATH . 'cert/apiclient_key.pem', // XXX: 绝对路径！！！！
            //'sandbox' => true,//沙盒模式
            'notify_url' => $arr['api_url'] . '/api/pay/xcxNotify', // 你也可以在下单时单独设置来想覆盖它
        ];
//        Log::error("小程序回调URL:".$config['notify_url']);
        $this->config = $config;
        $payment = Factory::payment($config);
        return $payment;
    }

    //公众号支付配置
    public function gzh_playConfig() {
        $sysConfig = getConfByType('basic');
        $arr['gzh_appid'] = $sysConfig['gzh_appid'];
        $arr['pay_num'] = $sysConfig['pay_num'];
        $arr['pay_key'] = $sysConfig['pay_key'];
        $arr['api_url'] = request()->domain();;
        $config = [
            // 必要配置
            'app_id' => $arr['gzh_appid'],
            'mch_id' => $arr['pay_num'],
            'key' => $arr['pay_key'], // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => ROOT_PATH .'/cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path' => ROOT_PATH .'/cert/apiclient_key.pem', // XXX: 绝对路径！！！！
            'notify_url' => $arr['api_url'] . '/api/pay/gzhnotify', // 你也可以在下单时单独设置来想覆盖它
        ];
        $payment = Factory::payment($config);
        return $payment;
    }

    //退款配置
    public function playConfig_back() {
        $sysConfig = getConfByType('basic');
        $arr['xcx_appid'] = $sysConfig['miniapp_app_id'];
        $arr['pay_num'] = $sysConfig['pay_num'];
        $arr['pay_key'] = $sysConfig['pay_key'];
        $arr['api_url'] = request()->domain();;

        $config = [
            // 必要配置
            'app_id' => $arr['xcx_appid'], 'mch_id' => $arr['pay_num'], 'key' => $arr['pay_key'], // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => ROOT_PATH . 'cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path' => ROOT_PATH . 'cert/apiclient_key.pem', // XXX: 绝对路径！！！！
            //'sandbox' => true,//沙盒模式
            'notify_url' => $arr['api_url'] . '/api/pay/tuiback', // 你也可以在下单时单独设置来想覆盖它
        ];

        $this->config = $config;
        $payment = Factory::payment($config);
        return $payment;
    }

    // 小程序支付
    public function play($money, $order_num, $sname = "购买物品消费",$openid) {
        $payment = self::playConfig();

       /* $sname = SysConfig::where('key', "merchant_name")->value('value');
        if (!$sname) {
            $sname = "点餐";
        }*/
        $res = $payment->order->unify([
            'body' => $sname,
            'out_trade_no' => $order_num,
            'total_fee' => $money,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
            $prepayId = $res['prepay_id'];
            $json = $payment->jssdk->bridgeConfig($prepayId);
            return $json;
        } else {
            trace_log($order_num.$sname."异常".json_encode($res),'paydata_except');
            $this->error_msg = $res['return_msg'];
            return false;
        }
    }

    /**
     * @param $transactionId 之前交易单号 order_no
     * @param $refundNumber  新的退款单号
     * @param $totalFee  总额
     * @param $refundFee 退款金额
     * @param array $config
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function tui($transactionId, $refundNumber, $totalFee, $refundFee, array $config = []) {
        $payment = self::playConfig_back();
        $res = $payment->refund->byOutTradeNumber($transactionId, $refundNumber, $totalFee, $refundFee, []);
        return $res;
    }



    // 公众号支付
    public function gzh_play($money, $order_num,$sname = "点餐消费",$openid) {
        $payment = self::gzh_playConfig();

        /* $sname = SysConfig::where('key', "merchant_name")->value('value');
         if (!$sname) {
             $sname = "点餐";
         }*/
//        $sname = "点餐消费";
        $res = $payment->order->unify([
            'body' => $sname,
            'out_trade_no' => $order_num,
            'total_fee' => $money,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);
        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
            $prepayId = $res['prepay_id'];
            $json = $payment->jssdk->bridgeConfig($prepayId);
            return $json;
        } else {
            trace_log($order_num.$sname."异常".json_encode($res),'paydata_except');
            $this->error_msg = $res['return_msg'];
            return false;
        }
    }
}
